package com.cks.msmservice.controller;

import com.cks.commonutils.R;
import com.cks.msmservice.service.MsmService;
import com.cks.msmservice.untils.RandomUtil;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {
    @Autowired
    private MsmService msmService;
   @Resource
   private RedisTemplate<String,String> redisTemplate;
    //发送短信的方法
    @GetMapping("send/{phone}")
     public R sendMsm(@PathVariable String phone ){
        //从redis中获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
             return R.ok();
        }
        //生成随机
        code= RandomUtil.getSixBitRandom();
        HashMap<String, Object> param = new HashMap<>();
        param.put("code",code);
       boolean isSend=msmService.send(param,phone);
       if (isSend){
           //设置redis 中验证码的有效时间
           redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES );
           return R.ok();
       }else {
           return R.error().message("发送短信失败");
       }
     }
}
